declare function send(jsonMsg);

class chatRoomWnd extends eui.Component {

    private bg:eui.Image;
    private textBtn:eui.Image;
    private soundBtn:eui.Image;
    private yybg:eui.Image;
    //private yywifi:eui.Image;
    private timeTx:eui.Label;
    private time:number = 0;
    private tatolTime:number = 15;
    private timer:egret.Timer = new egret.Timer(1000,this.tatolTime);
    private soundBtnClick:boolean = false;//语音按钮是否点击
    private CanSpeak:boolean = true;//可以说话
    private TextChat:boolean = true;//可以语音表情
    private isRecord:boolean = false;//是否在录音
    private textChat:TextChatWnd;

    //语音显示位置；DataString.chatPoint;//
    private ChatPoint:Array<any> = [{x:104.35,y:589.1},{x:1006.7,y:284.15},{x:791.9,y:12.35},{x:497.9,y:12.35},{x:196.45,y:12.35},{x:102.3,y:282.1}];
    private ChatObjList:Array<egret.MovieClip> = new Array();
    //表情显示位置 DataString.facePoint;//,
    private FacePoint:Array<any> =  [{x:92.7,y:587.6},{x:980.3,y:288.7},{x:768.05,y:51.15},{x:473.95,y:51.15},{x:186.25,y:51.15},{x:78.7,y:288.7}];
    private FaceObjList:Array<egret.MovieClip> = new Array();
    private thisInit:boolean = false;//第一次访问
    //文字语音位置
    //语音显示位置
    private ChatTxPoint:Array<any> = [{x:104.35,y:589.1},{x:1006.7,y:284.15},{x:791.9,y:12.35},{x:497.9,y:12.35},{x:196.45,y:12.35},{x:102.3,y:282.1}];
    private ChatTxObjList:Array<chathShowObjWnd> = new Array();
    private ChatTxOr:Array<string>=["left","right","up","left"];
    private ChatImageOr:Array<number>=[1,2,3,1];

    public constructor() {
		super();		
		this.addEventListener(eui.UIEvent.COMPLETE,this.onComplete,this);
        this.skinName = "src/Game/gameRoom/chat/chatRoom.exml";
        //GameData.FXOBJ.startRecord();//开始录音
       // GameData.FXOBJ.stopRecord();//停止录音
	}
	private onComplete():void{
       // console.log("语音界面加载完");

       //侦听地理位置数据
       StageData.FXOBJ.once("locationComplete",(e)=>{
           this.locationData = e.data;
           var str:string = '{"longitude":'+this.locationData.x+',"latitude":'+this.locationData.y+',"precision":'+this.locationData.a+',"secure":false,"time":0,"token":"'+GameData.token+'","type":200006,"version":"v1.0"}';          
           send(str);
       },this);
        //微信授权成功后再允许点击
        this.setCanSpeak(false); 
        StageData.FXOBJ.once("fxComplete",()=>{
            this.setCanSpeak(true);
        },this);
        //end
        
        this.removeEventListener(eui.UIEvent.COMPLETE,this.onComplete,this);
        
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.init,this);
        this.addEventListener(egret.Event.REMOVED_FROM_STAGE,this.onRemove,this);
        this.textChat = new TextChatWnd();
        this.textChat.anchorOffsetX = this.textChat.width/2;
        this.textChat.anchorOffsetY = this.textChat.height/2;
        this.textChat.x = 580;
        this.textChat.y = 360;    

        this.openRadio();   
        this.openRemind();
        /*StageData.MainObj.addEventListener("onRadio",(e)=>{
            this.setRadio(e.data);
        },this); */
        /*this.setRadio(["111卡社交恐惧离开家进度款发时刻都积分时刻就分手课件单发时刻都积分",
        "222卡社交恐惧离开家进度款发时刻都积分时刻就分手课件单发时刻都积分",
        "3333卡社交恐惧离开家进度款发时刻都积分时刻就分手课件单发时刻都积分",
        "4444卡社交恐惧离开家进度款发时刻都积分时刻就分手课件单发时刻都积分"]);
        
        this.setRemind("XXX的IP和XXX的相同");*/
	}
    //IP相同提醒
    private ipclew:playRemind;
    private openRemind(){
        if(this.ipclew){
            this.removeChild(this.ipclew);
        }
        this.ipclew = new playRemind();        
        this.ipclew.y = StageData.H - (this.ipclew.height*5)-10;
        this.addChild(this.ipclew);
    }
    private setRemind(msg){
        if(this.ipclew){
            this.ipclew.setContent(msg);
        }
    }

    //广播
    private radio:playRadio;
    private openRadio(){
        if(this.radio){
            this.removeChild(this.radio);
        }
        this.radio = new playRadio();
        this.radio.x = (StageData.W - this.radio.width)/2;
        this.radio.y = 50;
        this.addChild(this.radio);
    }
    private setRadio(msg){
        if(this.radio){
            this.radio.setContent(msg);
        }
    }

    //获取表情位置
    public get getChatPoint():Array<any>{
        return this.ChatPoint;
    }
    //设置表情位置
    public set setChatPoint(newPoint:Array<any>){
        this.ChatPoint = newPoint;
    }
    private pointObj:Array<number> = [0,1,2,3];
    //刷新表情语音显示位置
    public updatePoint(sendIndex:number,locationList:any){
        
        //alert("刷新表情位置:"+JSON.stringify(locationList));
        //if(!this.thisInit){
            if(!locationList) return;
            this.ChatPoint = locationList;
            this.FacePoint = locationList;
            this.ChatTxPoint = locationList

           for(var i:number=0;i<this.ChatObjList.length;i++){
                this.removeChild(this.ChatObjList[i]);
                this.removeChild(this.FaceObjList[i]);
                this.removeChild(this.ChatTxObjList[i]);
                //console.log("dd_");
            }
            this.pointObj = [0,1,2,3];
            this.ChatImageOr = [1,2,3,1];
            this.ChatObjList = [];
            this.FaceObjList = [];
            this.ChatTxObjList = [];
            
            for(var i:number=0;i<this.ChatPoint.length;i++){
                var qpao:egret.MovieClip = MyLibrary.createMovieClipByName("yy_qipao");
                qpao.x = this.ChatPoint[i].x;
                qpao.y = this.ChatPoint[i].y;
                qpao.gotoAndStop(this.ChatImageOr[i]);
                qpao.visible = false;
                this.ChatObjList.push(qpao);
                this.addChild(qpao);

                var Face:egret.MovieClip = MyLibrary.createMovieClipByName("yy_zk");
                Face.scaleX = Face.scaleY = 1.2;
                Face.x = this.FacePoint[i].x;//this.ChatPoint[i].x;
                Face.y = this.FacePoint[i].y;//this.ChatPoint[i].y-10;
                Face.frameRate = 12;
                //Face.gotoAndStop(i+1);
                Face.visible = false;
                this.FaceObjList.push(Face);
                this.addChild(Face);

                var chatTxobj:chathShowObjWnd = new chathShowObjWnd();
                //chatTxobj.setStr("...",this.ChatTxOr[i]);
                chatTxobj.x = this.ChatTxPoint[i].x;
                chatTxobj.y = this.ChatTxPoint[i].y;
                this.ChatTxObjList.push(chatTxobj);
                this.addChild(chatTxobj);
                chatTxobj.visible = false;
            }

            this.thisInit = true;
            this.pointObj = GameData.updatePoint(sendIndex,this.pointObj);
            this.FaceObjList = GameData.updatePoint(sendIndex,this.FaceObjList);
            this.ChatObjList = GameData.updatePoint(sendIndex,this.ChatObjList);
            this.ChatTxObjList = GameData.updatePoint(sendIndex,this.ChatTxObjList);
       // }        
    }
	
    private openTextChat(){
        this.bg.visible = true;
        this.addChild(this.textChat);
    }

    private closeTextChat(e){
        this.bg.visible = false;
        this.removeChild(this.textChat);
        //console.log("表情选择："+e.data);
        if(e.data){
            var str:string = '{"chat":{"chatType":2},"chatMsg":"'+e.data+'","secure":false,"token":"'+GameData.token+'","time":0,"type":200001,"version":"v1.0"}';
            send(str);
        }        
    }
    private timerUpdate(e:egret.TimerEvent){
        this.time --;
        this.timeTx.text = this.time+"'"
        if(this.time<=0){
            this.closeRecord();
        }
    }
    //登录服务器
    public login(){
        var str:string = '{"secure":false,"time":0,"token":"'+GameData.token+'","type":100000,"version":"v1.0"}';
        send(str); 
    }
    private init(){
      //  console.log("语音初始化");
        //登录聊天服务器
        /*var str:string = '{"secure":false,"time":0,"token":"'+GameData.token+'","type":100000,"version":"v1.0"}';
        send(str); */
        //alert("dddd");

        StageData.MainObj.addEventListener("sockMessage",this.getScokMsg,this);
        this.time = this.tatolTime;
        this.bg.visible = false;
        this.yybg.visible = false;
        this.timeTx.visible = false;
        //this.yywifi.visible = false;
        this.textBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.textClcik,this);
        this.soundBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.soundDown,this);
        this.addEventListener(egret.TouchEvent.TOUCH_END,this.soundUp,this);
        StageData.FXOBJ.addEventListener("STOP_RECORD",this.onRecoroStop,this);
        StageData.FXOBJ.addEventListener("UP_COMPLETE",this.onUpComplete,this);        
        this.timer.addEventListener(egret.TimerEvent.TIMER,this.timerUpdate,this);
        this.timer.addEventListener(egret.TimerEvent.COMPLETE,this.closeRecord,this);
        this.textChat.addEventListener("close",this.closeTextChat,this);
    }
    private textClcik(e:egret.TouchEvent){
        //console.log("文字聊天");
        //GameRoomWnd.Shared().addChatRoom();
        StageData.soundObj.startSound("down");
        this.openTextChat();
    }
    private soundDown(e:egret.TouchEvent){
        this.time = this.tatolTime; 
        StageData.MainObj.stopBgMusic();//录音时停止背景音乐
        //GameRoomWnd.Shared().addChatRoom();
        this.soundBtnClick = true;
        this.bg.visible = true;
        this.yybg.visible = true;
        this.timeTx.visible = true;
        //this.yywifi.visible = true;
        StageData.FXOBJ.startRecord();//录音
        this.isRecord = true;
        this.timeTx.text = this.time + "'"
        this.timer.start();
    }
    private soundUp(e:egret.TouchEvent){
        if(this.soundBtnClick){
            if(this.isRecord){
               this.closeRecord();
            }
            this.soundBtnClick = false;
        } 
    }
    //停止录音
    private closeRecord(){
         this.closeRecoro();
         StageData.MainObj.setBgMusic();//恢复背景音乐
         StageData.FXOBJ.stopRecord();//停止录音
    }
    private closeRecoro(){
        this.isRecord = false;
        this.bg.visible = false;
        this.yybg.visible = false;
        this.timeTx.visible = false;
        this.timer.reset();               
        //this.yywifi.visible = false;
    }
    //设置是否允许说话
    public setCanSpeak(_value:boolean){
        if(_value){
            this.soundBtn.source = "yy_ht1_png";
            this.soundBtn.touchEnabled = true;
        }else{
            this.soundBtn.source = "yy_ht2_png";
            this.soundBtn.touchEnabled = false;
        }
        this.CanSpeak = _value;
    }
    //设置是否允许语音表情
    public setChatSound(_value:boolean){
        if(_value){
            this.textBtn.alpha = 1;//this.textBtn.source = "yy_ht1_png";
            this.textBtn.touchEnabled = true;
        }else{
            this.textBtn.alpha = 0.5;//this.textBtn.source = "yy_ht2_png";
            this.textBtn.touchEnabled = false;
        }
        this.TextChat = _value;
    }

    private onRecoroStop(e){
        //当录音停止返回ID//及时通信传给后台  
        if(this.time<this.tatolTime){
            StageData.FXOBJ.uploadVoice(e.data);//微信上传
        }else{
            //StageData.GameRoot.ifClew("说话内容太短");
        }
        this.closeRecoro();        
    }
    private onUpComplete(e){
        //微信上传返回服务器ID
       // alert("TEST:"+e.data);//"sendId":"'+GameData.userData.sendId+'
        var str:string = '{"chat":{"chatType":"2"},"mediaId":"'+e.data+'","secure":false,"token":"'+GameData.token+'","time":0,"type":200000,"version":"v1.0"}';
        send(str);
    }

    //***** 接收显示*****/
    //显示表情 （座位号，内容）
    private conn1:any;private conn2:any;private conn3:any;private conn4:any;private conn5:any;private conn6:any;
    private conn1List:Array<any> = [this.conn1,this.conn2,this.conn3,this.conn4,this.conn5,this.conn6];
    private showFace(seatIndex:number,contStr:string){
       // alert(seatIndex+" : "+contStr);
        if(!seatIndex&&!contStr) return; 
        var lsFace:egret.MovieClip = MyLibrary.createMovieClipByName(contStr);
        var lsObj:egret.MovieClip = this.FaceObjList[seatIndex]; 
        lsObj.movieClipData = lsFace.movieClipData;

        StageData.soundObj.soundSinglePlay("dd");
        
        if(this.conn1List[seatIndex]){
            egret.clearTimeout(this.conn1List[seatIndex]);//清除定时器
        }
        lsObj.visible = true;
        lsObj.frameRate = 12;
        lsObj.play(-1);
        this.conn1List[seatIndex] = egret.setTimeout(()=>{
            egret.clearTimeout(this.conn1List[seatIndex]);//清除定时器
            this.setChatSound(true);
            this.conn1List[seatIndex] = null;
            lsObj.visible = false;
            lsFace = null;
            lsObj = null;
        },this,2000); 
    }
    private conn2obj:Array<number> = [0,0,0,0];
    //显示语音文字 （座位号，内容）
    private showVoice(seatIndex:number,contStr:string){
        if(!seatIndex&&!contStr) return;  
        var lsseatIndex =  seatIndex;             
        //alert(lsseatIndex);
        this.ChatTxObjList[lsseatIndex].visible = true;
        this.ChatTxObjList[lsseatIndex].setStr(contStr.split("_")[3],this.ChatTxOr[this.pointObj[seatIndex]]);
        
        var lssd = RES.getRes(contStr.split("_")[1]+"_mp3");
        var lsthis = this;
       
        var sdCh = lssd.play(0,1);
        if(StageData.soundClose){
            sdCh.volume = 1;
        }else{
            sdCh.volume = 0;
        }
        this.conn2obj[lsseatIndex] ++; 
        sdCh.addEventListener(egret.Event.SOUND_COMPLETE,(e) =>{
            lsthis.conn2obj[lsseatIndex] --;
            if(lsthis.conn2obj[lsseatIndex] <= 0){
               lsthis.ChatTxObjList[lsseatIndex].visible = false;
               this.setChatSound(true);
            }
        },this);
    }

    //显示语音 （座位号，链接URL）
    private chatList:Array<number> = [0,0,0,0];
    private showChat(seatIndex:number,urlStr:string){
        if(!seatIndex&&!urlStr) return; 
        var lsseatIndex =  seatIndex;             
        var lsthis = this;
        this.ChatObjList[lsseatIndex].visible = true;
       
        RES.getResByUrl(urlStr,(e) =>{
            var soundUIObj = lsthis.ChatObjList[lsseatIndex];
            var lssound:egret.Sound = e;
            var lsSoundCh:egret.SoundChannel;
            lsSoundCh = lssound.play(0,1); 
            //this.chatList[lsseatIndex] ++; 
            lsSoundCh.addEventListener(egret.Event.SOUND_COMPLETE, (e) =>{
                 //soundUIObj.visible = false;
                    //lsthis.chatList[lsseatIndex] --;
                    //if(lsthis.chatList[lsseatIndex] <= 0){
                       lsthis.ChatObjList[lsseatIndex].visible = false;
                    //}
                 this.setCanSpeak(true);  
            },this);
        },RES.ResourceItem.TYPE_SOUND);   
    }
    private conn3obj:any; 

    private getScokMsg(e){       
       
       var msg:any = e.data;//msg.error.errorMsg
       if(!msg) return;
       //console.log("ChatGetScok:"+JSON.stringify(e.data));
				switch(msg.type) {
						case 200000://接收语音
                        if(msg.errorCode == 0){
                            if(msg.videoUrl){
                                if(msg.chat.sendIndex == GameData.mySeatIndex){
                                    this.setCanSpeak(false);
                                }
                                this.showChat(msg.chat.sendIndex,msg.videoUrl);
                            }
                        }else{
                            StageData.GameRoot.ifClew("语言发送失败，请重试");
                            this.setCanSpeak(true);
                        }
                        break;

                        case 200005://接收距离信息
                           // alert("玩家距离信息:"+JSON.stringify(msg));
                            this.setLocation(msg);
                        break;

                        case 200002://同IP提示
                            if(msg){
                                this.setRemind(msg.data);
                            }                             
                        break;

                        case 200003://广播消息                        
                            if(msg){
                                this.setRadio(msg.data);
                            }                        
                        break;
                        case 200001://接收文字
                        var lsStr:string = msg.chatMsg;
                        if(msg.chat.sendIndex == GameData.mySeatIndex){
                                this.setChatSound(false);
                        }  
                        if(lsStr.split("_")[0]=="chat"){
                            //this.setChatSound(false);
                            //this.setCanSpeak(false);              
                            this.showVoice(msg.chat.sendIndex,lsStr);
                        }
                        if(lsStr.split("_")[0]=="face"){
                            this.showFace(msg.chat.sendIndex,lsStr.split("_")[1]);
                        }
                        break;
						default:
				}
    }   
    
    private onRemove(e:egret.Event){
        StageData.MainObj.removeEventListener("sockMessage",this.getScokMsg,this);
        this.textBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.textClcik,this);
        this.soundBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN,this.soundDown,this);
        this.removeEventListener(egret.TouchEvent.TOUCH_END,this.soundUp,this);
        this.removeEventListener(egret.Event.REMOVED_FROM_STAGE,this.onRemove,this);
        this.removeEventListener(egret.Event.ADDED_TO_STAGE,this.init,this);
        this.timer.removeEventListener(egret.TimerEvent.TIMER,this.timerUpdate,this);
        this.timer.removeEventListener(egret.TimerEvent.COMPLETE,this.closeRecord,this);
        StageData.FXOBJ.removeEventListener("STOP_RECORD",this.onRecoroStop,this); 
        StageData.FXOBJ.removeEventListener("UP_COMPLETE",this.onUpComplete,this);         
        this.textChat.removeEventListener("close",this.closeTextChat,this);
        this.timer = null;
        //console.log("语音聊天功能被清除");
    }

    private locationobj:locationwnd;
    private locationData;
    //设置地理数据
    public setLocation(_data:any){
        if(this.locationobj&&this.locationData){
            this.locationobj.setContent(_data.dists);
        }
    }

    //获取距离信息
    public sendGetLocation(userid:number){//用户ID
        this.openLocation();//打开地理位置
        var str:string = '{"lftid":"'+userid+'","secure":false,"time":0,"token":"'+GameData.token+'","type":200005,"version":"v1.0"}';          
           send(str);
    }

    public openLocation(){
        //if(!this.locationData) return;
        this.closeLocation();
        this.locationobj = new locationwnd();        
        this.addChild(this.locationobj);
        this.locationobj.once("close",this.closeLocation,this);
    }

    private closeLocation(){
        if(this.locationobj){
            this.removeChild(this.locationobj);
            this.locationobj = null;
        }
    }
}

